package mysql

import (
	"furni-mgr/furnirpc/furnirpc"
	"gorm.io/gorm"
)

type Furniture struct {
	gorm.Model
	FurnitureName  string  `gorm:"type:varchar(30);not null;comment:'家具名称'"`
	FurniturePrice float64 `gorm:"type:decimal(10,2);not null;comment:'家具价格'"`
	BrandId        int64   `gorm:"type:int(11);not null;comment:'品牌编号'"`
	ClassId        int64   `gorm:"type:int(11);not null;comment:'类型编号'"`
}

type ShowFurniture struct {
	gorm.Model
	FurnitureName  string  `gorm:"type:varchar(30);not null;comment:'家具名称'"`
	FurniturePrice float64 `gorm:"type:decimal(10,2);not null;comment:'家具价格'"`
	BrandName      string  `gorm:"type:varchar(30);not null;comment:'品牌名称'"`
	ClassName      string  `gorm:"type:varchar(30);not null;comment:'类型名称'"`
}

func (f *Furniture) FurnitureAdd(db *gorm.DB) error {
	return db.Debug().Create(f).Error
}

func FurnitureShow(db *gorm.DB, id int64) (ShowFurniture, error) {
	var furniture ShowFurniture

	err2 := db.Debug().Table("furnitures").Select(
		"furnitures.id",
		"furnitures.furniture_name",
		"furnitures.furniture_price",
		"brands.brand_name",
		"classes.class_name",
	).Joins("LEFT JOIN brands ON furnitures.brand_id=brands.id").
		Joins("LEFT JOIN classes ON furnitures.class_id=classes.id").
		Where("furnitures.id=?", id).
		First(&furniture).Error

	return furniture, err2
}

/*
SELECT
furnitures.id,
furnitures.furniture_name,
furnitures.furniture_price,
brands.brand_name,
classes.class_name
FROM furnitures
LEFT JOIN brands ON furnitures.brand_id=brands.id
LEFT JOIN classes ON furnitures.class_id=classes.id
*/

func FurnitureList(db *gorm.DB) ([]*furnirpc.FurnitureList, error) {
	var furniture []*furnirpc.FurnitureList

	err2 := db.Debug().Model(&Furniture{}).Select(
		"furnitures.id as furniture_id",
		"furnitures.furniture_name",
		"furnitures.furniture_price",
		"brands.brand_name",
		"classes.class_name",
	).Joins("LEFT JOIN brands ON furnitures.brand_id=brands.id").
		Joins("LEFT JOIN classes ON furnitures.class_id=classes.id").
		Find(&furniture).Error

	return furniture, err2
}
